package com.yeskery.nut.cloud.registry.core;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;

/**
 * 默认内置实例注册器
 * @author YESKERY
 * 2024/1/4
 */
public class DefaultServerInstanceRegistry implements ServerInstanceRegistry {

    /** 日志对象 */
    private static final Logger logger = Logger.getLogger(DefaultServerInstanceRegistry.class.getName());

    /** 递增器 */
    private final AtomicInteger atomic = new AtomicInteger(0);

    /** 服务 */
    private Server server;

    /** 服务实例 */
    private volatile List<Instance> instances = new ArrayList<>();

    @Override
    public Server getServer() {
        return server;
    }

    @Override
    public Collection<Instance> getInstances() {
        return instances;
    }

    @Override
    public void registerInstance(ServerInstanceMetadata metadata) {
        if (contains(metadata)) {
            logger.info("Server[" + server.name() + "], Instance[scheme(" + metadata.getScheme() + "), ip("
                    + metadata.getIp() + "), port(" + metadata.getPort() + ") Already Registered.");
            return;
        }
        List<Instance> copyInstances = new ArrayList<>(instances);
        DefaultInstance instance = new DefaultInstance();
        instance.setId(String.valueOf(atomic.incrementAndGet()));
        instance.setServerInstanceMetadata(metadata);
        copyInstances.add(instance);
        instances = copyInstances;
        logger.info("Server[" + server.name() + "], Instance[scheme(" + metadata.getScheme() + "), ip("
                + metadata.getIp() + "), port(" + metadata.getPort() + ") Registered.");
    }

    @Override
    public boolean contains(ServerInstanceMetadata metadata) {
        return instances.stream().anyMatch(r -> r.getScheme().equals(metadata.getScheme())
                && r.getIp().equals(metadata.getIp()) && r.getPort().equals(metadata.getPort()));
    }

    @Override
    public void removeInstance(String id) {
        List<Instance> copyInstances = new ArrayList<>(instances);
        copyInstances.removeIf(instance -> instance.id().equals(id));
        instances = copyInstances;
    }

    /**
     * 设置服务对象
     * @param server 服务对象
     */
    public void setServer(Server server) {
        this.server = server;
    }
}
